﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TileMap
{
    class MapCellDown
    {
        private static readonly System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
        public int Row { get; set; }
        public int Column { get; set; }
        public int Zoom { get; set; }

        public Image MapImage { get; private set; }

        public async Task GetImageAsync(IMapTileFilter filter)
        {
            try
            {
                var response = await client.GetAsync(GetTencentMapUrl());
                response.EnsureSuccessStatusCode();
                var data = await response.Content.ReadAsStreamAsync();
                MapImage = null;
                MapImage = Image.FromStream(data);
                if (filter != null)
                {
                    filter.Filter(MapImage, Row, Column);
                }
                MapImage.Dispose();
                MapImage = null;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }
         
        private string GetTencentMapUrl()
        {
            int r = (int)Math.Floor(Row / 16.0f);
            int c = (int)Math.Floor(Column / 16.0f);
            return string.Format(@"https://p0.map.gtimg.com/sateTiles/{0}/{1}/{2}/{3}_{4}.jpg?version=229",
                Zoom, c, r, Column, Row);
        }
    }
}
